var express = require('express')
var router = express.Router()
const UserModel = require('../../models/UserModel')
const md5 = require('md5')
// 注册
router.get('/reg', (req, res) => {
  // 响应 HTML 内容
  res.render('auth/reg')
})
router.post('/reg', (req, res) => {
  // 响应 HTML 内容
  // 获取请求体的数据
  UserModel.create(
    { ...req.body, password: md5(req.body.password) },
    (err, data) => {
      if (err) {
        return res.status(500).send('register fail, please try again')
      }
      res.render('result/success', { msg: '注册成功', url: '/login' })
    }
  )
  console.log(req.body)
  res.send('register success')
})

// 登录
router.get('/login', (req, res) => {
  // 响应 HTML 内容
  res.render('auth/login')
})
// 登录
router.post('/login', (req, res) => {
  // 获取用户名和密码
  let { username, password } = req.body
  // 查询数据库
  UserModel.findOne({ username, password: md5(password) }, (err, data) => {
    if (err) {
      return res.status(500).send('login fail, username or password error')
    }
    if (!data) {
      return res.send('login fail, username or password error')
    }
    // save session
    req.session.username = data.username
    req.session._id = data._id
    // login succsee
    res.render('result/success', { msg: '登录成功', url: '/account' })
  })
})
// 退出登录
router.post('/logout', (req, res) => {
  // 销毁  session
  req.session.destroy(() => {
    res.render('result/success', { msg: '退出成功', url: '/login' })
  })
})

module.exports = router
